<!-- 指标配置-添加&编辑页 -->
<template>
  <view class="s-list">
    <Header :title="title" bgColor="#fff" :leftIconSize="20"/>
    <!-- 搜索 -->
    <view class='s-box pad25 s-form-box'>
      <uv-form labelPosition="left" :model="formData" ref="rForm">
        <uv-form-item :label="indicatorTypeLabel" borderBottom labelWidth='150' @click="showPicker">
          <template v-slot:right v-if="!editFlag">
            <uv-icon name="arrow-right"/>
          </template>
        </uv-form-item>
        <uv-form-item  label="" @click="showNameSelect">
          <template #label>
            <div class="requireStar">指标名称</div>
          </template>
          <uv-textarea v-model="formData.name" :maxlength="-1" autoHeight disabled placeholder="请输入指标名称" border='none' maxlength="30"></uv-textarea>
          <template v-slot:right>
            <uv-icon name="arrow-right"/>
          </template>
        </uv-form-item>
      </uv-form>
    </view>
    <!-- 主内容 -->
    <view class='s-list-main s-box s-check-main'>
      <view class='s-all-check'>
        <view class="num">序号</view>
        <view class="name">检查项目及内容</view>
        <view class="s-check" style="margin-right: 0rpx;width:130rpx;">
          <!--<uv-checkbox-group iconPlacement="right" placement="column">-->
            <!--<uv-checkbox :checked="allCheck" name="apple" label="全选" @change="allChecked"/>-->
          <!--</uv-checkbox-group>-->
          <checkbox-group @change="allChecked">
            <label class="cu-checked-group">
              <text class="text">全选</text>
              <checkbox hidden color="#FFFFFF" value="2" />
              <view class="cu-checkbox" v-if="checkType!==2" :class="checkType===1 ? 'check-not-full' : (checkType===2 ? 'check-full': 'check-not')">
                <view class="uni-checkbox-input"></view>
              </view>
              <view class="cu-checkbox check-full iconfont icon-duihao41" v-if="checkType===2">
              </view>
            </label>
          </checkbox-group>
        </view>
      </view>
      <view class='s-check-bottom'>
        <daTree ref="DaTreeRef" :data="treeData" labelField="content" valueField="id" expandChecked showCheckbox
                :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange">
        </daTree>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class='s-btn-common'>
      <uv-button type="primary" text="确认" :disabled="loading" @click="confirmFun()"/>
    </view>
    <!-- 指标类型的下拉 -->
    <uv-action-sheet ref="indicatorType" title="指标类型" :closeOnClickOverlay="false" :closeOnClickAction="false" @close="close">
      <slot>
        <view class="search-picker-main">
          <view v-for="(item,index) in indicatorTypeColumns" :key="index" class="search-picker"
                :class="activeIndex===index?'search-picker-active':''" @click="pickerFun(item,index)">
            {{ item.name }}
          </view>
          <view class='s-btn-common'>
            <uv-button type="primary" text="确认" @click="indicatorTypeConfirm()"/>
          </view>
        </view>
      </slot>
    </uv-action-sheet>
    <!-- 指标名称 -->
    <uv-action-sheet ref="indicatorName" title="指标名称" :closeOnClickOverlay="false" :closeOnClickAction="false" @close="indicatorNameClose">
      <slot>
        <view class="search-picker-main">
          <view class='textarea-main'>
            <uv-textarea v-model="indicatorNameValue" count placeholder="请输入指标名称" height='200rpx' maxlength="30"/>
            <image :src="imgMinioPath + '/law/yuyin.png'" @click="showSpeech"></image>
          </view>
          <view class='s-btn-common'>
            <uv-button type="primary" text="确认" @click="indicatorNameConfirm()"/>
          </view>
        </view>
      </slot>
    </uv-action-sheet>
    <!--    唤起语音    -->
    <view style="height: 0">
      <uv-popup ref="refSpeech" mode="bottom" round="8">
        <speech-recognition @getSpeeckInfo="getSpeeckInfo" :maxlength="30"></speech-recognition>
      </uv-popup>
    </view>
  </view>
</template>

<script setup>
  import entryAPI from "@/api/law/entry/entry";
  import targetAPI from '@/api/law/target/target';
  import targetEntryAPI from "@/api/law/target/targetEntry";
  import {deepClone} from './data';
  import {onLoad} from '@dcloudio/uni-app';
  import {ref, reactive, getCurrentInstance, defineProps, computed} from 'vue';
  import config from "@/common/config";
  let imgMinioPath = ref(config.IMG_MINIO_PATH);

  const {proxy} = getCurrentInstance();
  const props = defineProps({
    row: {
      type: Object,
      default: () => {
        return {};
      }
    },
    editFlag: {
      required: false,
      type: Boolean,
      default: false
    },
    entryType: {
      required: false,
      type: String,
      default: ''
    }
  });

  let rForm = ref();
  let title = ref('添加');
  let loading = ref(false);
  let userInfo = ref(uni.getStorageSync('userInfo'));
  let formData = reactive({
    name: "",
    entryType: "",
    createOrgId: userInfo.value.user.orgId,
    entryIds: [],
  });
  let rules = reactive({
    name: [{
      type: 'string',
      required: true,
      message: '请输入指标名称',
      trigger: ['change']
    }],
  });

  /** 数据加载 */
  onLoad(async (e) => {
    if (e.editFlag) {
      title = ref('编辑');
      if (e.row) {
        Object.assign(formData,JSON.parse(decodeURIComponent(e.row)))
        await getTargetEntryList();
      }
    } else {
      title = ref('添加');
      formData.entryType = e.entryType;
    }
    if (formData.entryType === '1') {
      activeIndex.value = 0;
      indicatorTypeLabel.value = '食品安全检查指标';
    } else if (formData.entryType === '2') {
      activeIndex.value = 1;
      indicatorTypeLabel.value = '校园安全检查指标';
    } else if (formData.entryType === '3') {
      activeIndex.value = 2;
      indicatorTypeLabel.value = '食堂自查指标';
    } else if (formData.entryType === '4') {
      activeIndex.value = 3;
      indicatorTypeLabel.value = '校园自查指标';
    } else if (formData.entryType === '5') {
      activeIndex.value = 4;
      indicatorTypeLabel.value = '配餐单位自查指标';
    } else if (formData.entryType === '6') {
      activeIndex.value = 5;
      indicatorTypeLabel.value = '配餐单位食品安全检查指标';
    } else if (formData.entryType === '7') {
      activeIndex.value = 6;
      indicatorTypeLabel.value = '学校有害生物防治检查指标';
    } else if (formData.entryType === '8') {
      activeIndex.value = 7;
      indicatorTypeLabel.value = '学校有害生物防治自查指标';
    }
    await getEntryList();
    await getEntryTreeList();
  });

  /** 获取指标列表 */
  const entryList = ref([]);
  let getEntryList = async () => {
    let res = await proxy.http.asyncPost(entryAPI.entryPage, formData);
    if (res.code === 0) {
      entryList.value = res.data.records;
      allCheck.value = entryList.value.length === selectKeys.value.length;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 获取指标树列表 */
  const entryTreeList = ref([]);
  let getEntryTreeList = async () => {
    let res = await proxy.http.asyncPost(entryAPI.entryTreeList, formData);
    if (res.code === 0) {
      entryTreeList.value = res.data;
      treeData.value = deepClone(entryTreeList.value);
      changeCss();
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 获取已选检查项-编辑回显 */
  let selectKeys = ref([]);
  let getTargetEntryList = async () => {
    let res = await proxy.http.asyncPost(targetEntryAPI.targetEntryPage, {targetId: formData.id});
    if (res.code === 0) {
      selectData.value = [...res.data.records.map(item => item.entryId)];
      defaultCheckedKeysValue.value = selectData.value;
      selectKeys.value = selectData.value
      doCheckedTree(selectKeys.value)
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 指标类型下拉 */
  const indicatorType = ref(); // 实例化
  const activeIndex = ref(0);
  const indicatorTypeLabel = ref('食品安全检查指标');
  const indicatorTypeColumns = ref([
    {
      id: '1',
      name: '食品安全检查指标',
    }, {
      id: '2',
      name: '校园安全检查指标',
    }, {
      id: '3',
      name: '食堂自查指标'
    }, {
      id: '4',
      name: '校园自查指标'
    }, {
      id: '5',
      name: '配餐单位自查指标'
    },
    {
      id: '6',
      name: '配餐单位食品安全检查指标'
    }
  ]);
  // 下拉-打开
  const showPicker = () => {
    if (!props.editFlag) {
      indicatorType.value.open();
    }
  };
  // 下拉-取消
  const close = () => {
  };
  // 下拉-点击
  const pickerFun = (item, index) => {
    activeIndex.value = index;
    formData.entryType = item.id;
  };
  // 下拉-确认
  const indicatorTypeConfirm = () => {
    indicatorTypeLabel.value = indicatorTypeColumns.value[activeIndex.value].name;
    formData.entryType = indicatorTypeColumns.value[activeIndex.value].id;
    getEntryTreeList();
    defaultCheckedKeysValue.value = [];
    allCheck.value = entryList.value.length === selectKeys.value.length;
    indicatorType.value.close();
    selectData.value = [];
    checkType.value = 0;
  };

  /** 指标名称下拉 */
  const indicatorNameValue = ref('');
  const indicatorName = ref(null);
  // 下拉-打开
  const showNameSelect = () => {
    indicatorNameValue.value = formData.name;
    indicatorName.value.open();
  };
  // 下拉-确认
  const indicatorNameConfirm = () => {
    formData.name = indicatorNameValue.value;
    indicatorName.value.close();
  };
  // 下拉-关闭
  const indicatorNameClose = () => {};

  /** 添加功能 **/
  let save = async () => {
    uni.showModal({
      title: '温馨提示',
      content: '确定添加该条数据？',
      success: async function (res) {
        if (res.confirm) {
          let res = await proxy.http.asyncPost(targetAPI.targetAdd, formData);
          if (res.code === 0) {
            await uni.showToast({icon: 'success', title: '添加成功', duration: 2000});
            loading.value = true;
            setTimeout(() => {
              goBack();
            }, 1000)
          } else {
            await uni.showToast({title: res.msg, icon: 'none'});
          }
        }
      }
    })
  };

  /** 编辑功能 **/
  let update = async () => {
    uni.showModal({
      title: '温馨提示',
      content: '确定编辑该条数据？',
      success: async function (res) {
        if (res.confirm) {
          let res = await proxy.http.asyncPost(targetAPI.targetEdit, formData);
          if (res.code === 0) {
            await uni.showToast({icon: 'success', title: '编辑成功', duration: 2000});
            loading.value = true;
            setTimeout(() => {
              goBack();
            }, 1000)
          } else {
            await uni.showToast({title: res.msg, icon: 'none'});
          }
        }
      }
    })
  };

  /** 确认提交 **/
  const confirmFun = () => {
    loading.value = false;
    rForm.value.validate().then(() => {
      if (formData.name === '') {
        uni.showToast({
          title: '请输入指标名称',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (selectData.value.length === 0) {
        uni.showToast({
          title: '请选择检查项',
          icon: 'none',
          duration: 2000
        })
        return
      }
      formData.entryIds = selectData.value;
      if (props.editFlag) {
        update();
      } else {
        save();
      }
    });
  };

  /** 树组件 */
  const DaTreeRef = ref();
  const treeData = ref([]);
  const selectData = ref([]);
  const defaultCheckedKeysValue = ref([]) // 多选时默认值为数组
  const allCheck = ref(false); // 全选

  // 计算递归数组的长度
  const totalCount = computed(() => {
    let count = 0;
    const recurseArray = (arr) => {
      arr.forEach(item => {
        count++;
        if (item.children) {
          recurseArray(item.children);
        }
      });
    };
    recurseArray(entryTreeList.value);
    return count;
  });
  // id集合
  const idArray = computed(() => {
    let allArray = [];
    const recurseArray = (arr) => {
      arr.forEach(item => {
        allArray.push(item.id);
        if (item.children) {
          recurseArray(item.children);
        }
      });
    };
    recurseArray(entryTreeList.value);
    return allArray;
  });
  // 全选
  const allChecked = () => {
    allCheck.value = !allCheck.value;
    if (allCheck.value === true) {
      //id全选上
      defaultCheckedKeysValue.value = idArray.value
      selectData.value = idArray.value
    } else {
      defaultCheckedKeysValue.value = []
      selectData.value = [];
    }
    changeCss();
  };
  let checkType = ref(0)
  const changeCss = () =>{
    if(!selectData.value.length){
      checkType.value = 0//未选
    }else if(idArray.value.length == selectData.value.length){
      checkType.value = 2//全选
    }else{
      checkType.value = 1//半选
    }
  }
  // 复选按钮
  const handleTreeChange = (values, currentItem) => {
    // 支持修改节点数据
    allCheck.value = values.length === totalCount.value;
    selectData.value = values;
    defaultCheckedKeysValue.value = values;
    // console.log('handleTreeChange ==>', values, currentItem)
    changeCss();
  };
  // 回显赋值
  const doCheckedTree = (keys, checked) => {
    DaTreeRef.value?.setCheckedKeys(keys, checked)
  };

  /** 返回上一页 */
  let goBack = async () => {
    uni.$emit("refresh", {});
    await uni.navigateBack();
  };

  /** 语音输入 */
  const refSpeech = ref();
  const showSpeech = () => {
    refSpeech.value.open();
  };

  function getSpeeckInfo(val) {
    refSpeech.value.close();
    indicatorNameValue.value += val;
  }
</script>

<style scoped lang="scss">

.textarea-main {
  position: relative;
  & > image {
    position: absolute;
    bottom: 10rpx;
    right: 120rpx;
    height: 50rpx;
    width: 50rpx;
  }
}
::v-deep .s-form-box .item__body__right__content__icon {
  margin-left: 0 !important;
}
::v-deep .uv-form-item__body{
  align-items: center !important;
}
.cu-checked-group {
  padding-top: 10px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: normal;
  justify-content: space-between;
  /*border-bottom: 1px #eee solid;*/

  .text{
    margin-right: 5px;
    color: #303133;
    font-size: 16px !important;
  }
}
.cu-checkbox{
  font-family: uvicon-iconfont;
  position: relative;
  width: 34rpx;
  height: 34rpx;
  border: 1px solid #DCDFE6;
  /*border-radius: 3px;*/
  background-color: #fff;
  box-sizing: border-box;
  &.check-not {
    border: 2px solid #DCDCDC;
    background-color: #fff;
  }

  &.check-not-full {
    border-color: #3775F6;
    background-color: #3775F6;
    .uni-checkbox-input {
      position: absolute;
      /* #ifndef APP-NVUE */
      top: 3px;
      /* #endif */
      left: 3px;
      height: 6px;
      width: 10px;
      border-bottom-width: 2px;
      border-bottom-color: #e7e7e7;
      border-bottom-style: solid;
      transform-origin: center;
    }

  }

  &.check-full {
    border-color: #007aff;
    background-color: #007aff;
    .uni-checkbox-input image{
      width: 12px;
      height: 10px;
      margin-left: 2px;
      margin-top: 3px;
    }
  }
}
.icon-duihao1:before {
  font-size: 12px !important;
  bottom: 2px;
  left: 2px
}
  .s-all-check {
    width: calc(100vw - 48rpx);
    margin: 0 auto;
    padding: 0 24rpx;
    .num{
      width: 150rpx;
    }
  }
</style>
